import numpy as np
import cv2
from copy import deepcopy


def calWeight(d, k):
    '''

    :param d: 融合重叠部分直径
    :param k: 融合计算权重参数
    :return:
    '''

    x = np.arange(-d / 2, d / 2)
    y = 1 / (1 + np.exp(-k * x))
    return y


def imgFusion(img1, img2, overlap, left_right=True):
    '''
    图像加权融合
    :param img1:
    :param img2:
    :param overlap: 重合长度
    :param left_right: 是否是左右融合
    :return:
    '''
    # 这里先暂时考虑平行向融合
    w = calWeight(overlap, 0.1)  # k=5 这里是超参

    if left_right:  # 左右融合
        row_1, col_1 = img1.shape[0:2]
        row_2, col_2 = img2.shape[0:2]
        img_new = np.zeros((row_1, col_1 + col_2 - overlap, img1.shape[2]))
        img_new[:, :col_1, :] = img1
        w_expand = np.tile(w, (row_1, 1))  # 权重扩增
        for i in range(img1.shape[2]):
            img_new[:, col_1 - overlap:col_1,
                    i] = (1 - w_expand) * img1[:, col_1 - overlap:col_1, i] + w_expand * img2[:, :overlap, i]
        img_new[:, col_1:, :] = img2[:, overlap:, :]
    else:  # 上下融合
        row_1, col_1 = img1.shape[0:2]
        row_2, col_2 = img2.shape[0:2]
        img_new = np.zeros((row_1 + row_2 - overlap, col_1, img1.shape[2]))
        img_new[:row_1, :, :] = img1
        w = np.reshape(w, (overlap, 1))
        w_expand = np.tile(w, (1, col_1))
        for i in range(img1.shape[2]):
            img_new[row_1 - overlap:row_1, :,
                    i] = (1 - w_expand) * img1[row_1 - overlap:row_1, :, i] + w_expand * img2[:overlap, :, i]
        img_new[row_1:, :, :] = img2[overlap:, :, :]
    return img_new


if __name__ == "__main__":
    image = cv2.imread(r"3.jpg", cv2.IMREAD_UNCHANGED)

    # 取图片信息
    shape = image.shape
    # 行数
    row = shape[0]
    # 列数
    col = shape[1]
    # 设置目标框左上角原点位置
    origin_X = 800
    origin_Y = 800
    assert origin_X < row and origin_Y < col, "origin should less than ({}, {}}".format(row, col)
    # 设置 设置图片行列重复次数
    row_num = 3
    col_num = 3
    # 先横向拼接
    image_tmp = deepcopy(image)
    for i in range(row_num + 1):
        image_tmp = imgFusion(image_tmp, image, overlap=800, left_right=False)
    image_new = deepcopy(image_tmp)
    for i in range(col_num + 1):
        image_new = imgFusion(image_new, image_tmp, overlap=800, left_right=True)
    # 切分
    img_new = image_new[origin_X:origin_X + row_num * row, origin_Y:origin_Y + col_num * col, :]
    cv2.imwrite(r'result.png', img_new)
